package com.da.lon.wang.xlg.adapter;

import android.content.Context;
import android.support.v4.view.PagerAdapter;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewParent;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;

import com.da.lon.wang.xlg.R;
import com.da.lon.wang.xlg.bean.HomeResultBean.HomeItemContentBean;
import com.da.lon.wang.xlg.util.Utils;

import java.util.ArrayList;

public class AdPageAdapter extends PagerAdapter {

    ImageView imageView;
    private LayoutInflater inflater;
    private ArrayList<HomeItemContentBean> list;
    private Context context;
    private int index;

    public AdPageAdapter(Context context, ArrayList<HomeItemContentBean> list) {
        this.list = list;
        this.context = context;
        inflater = LayoutInflater.from(context);
    }

    @Override
    public int getCount() {
        if (list == null) {
            return 0;
        } else {
            return Integer.MAX_VALUE;
        }
    }

    @Override
    public boolean isViewFromObject(View arg0, Object arg1) {
        return arg0 == ((View) arg1);
    }

    @Override
    public Object instantiateItem(ViewGroup container, final int position) {
        try {
            index = position % list.size();
            if (position < 0) {
                index = list.size() + position;
            }
            imageView = (ImageView) inflater.inflate(R.layout.ocoffee_ad_item,
                    null);
            imageView.setScaleType(ScaleType.FIT_XY);
            ViewParent vp = imageView.getParent();
            if (vp != null) {
                ViewGroup parent = (ViewGroup) vp;
                parent.removeView(imageView);
            }
            if (list.get(index) != null && !"".equals(list.get(index))) {
                Utils.loadImageByGlide(context, list.get(index).getImg_url(), null, imageView, 0, 0, 0);
            }
            imageView.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                    int index1 = position % list.size();
                    Utils.onClickBannerStartActivity(context,
                            Integer.parseInt(list.get(index1).getStatus()),
                            list.get(index1).getLink());

                }
            });

            container.addView(imageView);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return imageView;
    }

    @Override
    public void destroyItem(ViewGroup container, int position, Object object) {
        container.removeView((View) object);
    }
}
